import csv,time

search_count = 0  # 统计正确查询次数
incorrect_count = 0  # 统计不正确的查询次数
sum_count = 0
data = []  # 定义一个空列表，存储BMI计算数据

# 将数据保存到CSV文件
filename = "bmi_data.csv"   # 文件名
# 打开文件bmi_data.csv
# "a" 模式将文件以追加模式打开，使用 newline="" 以确保在写入文件时不添加额外的换行符。
with open(filename, "a", newline="") as file:
    # 创建一个 csv.writer 对象 writer，并将其与文件对象 file 关联，可以使用该对象来写入 CSV 数据。
    writer = csv.writer(file)
    # 检查文件是否为空，如果为空则写入表头
    if file.tell() == 0:
        # 输入表头
        writer.writerow(["姓名", "身高(米)", "体重(公斤)", "年龄", "性别", "BMI","国际","国内","查询时间"])

    while True:
        name = input('请键入您的姓名:')
        try:
            height, weight = map(float, input("请输入身高(米)和体重(公斤)[逗号隔开]: ").split(','))
            age = int(input("请输入年龄: "))
            if age <= 0:
                raise ValueError
        except ValueError:
            print("输入格式错误，请重新输入")
            incorrect_count += 1
            continue

        gender = input('请键入你的性别(f/m)')
        bmi = weight / (height ** 2)

        if bmi < 18.5:
            who, nat = "偏瘦", "偏瘦"
        elif 18.5 <= bmi < 24:
            who, nat = "正常", "正常"
        elif 24 <= bmi < 25:
            who, nat = "正常", "偏胖"
        elif 25 <= bmi < 28:
            who, nat = "偏胖", "偏胖"
        elif 28 <= bmi < 30:
            who, nat = "偏胖", "肥胖"
        else:
            who, nat = "肥胖", "肥胖"

        print("BMI 指标为:国际'{0}', 国内'{1}'".format(who, nat))

        nowtime = time.asctime(time.localtime(time.time()))
        if gender == 'f':
            print('感谢', name, '女士在', nowtime, '使用本程序,祝您身体健康!')
        elif gender == 'm':
            print('感谢', name, '先生在', nowtime, '使用本程序,祝您身体健康!')
        else:
            print("无效的性别，请重新输入")
            incorrect_count += 1
            continue

        search_count += 1
        data.append([name, height, weight, age, gender, bmi, who, nat, nowtime])

        user_input = input("输入 'n' 停止循环: ")
        if user_input == 'n':
            break

    sum_count = search_count + incorrect_count
    print("您的查询次数为", sum_count, "次")
    print("其中正确的查询次数为", search_count, "次")
    print("其中不正确的查询次数为", incorrect_count, "次")

    # data只是一行一行数据，writer.writerows(data)将列表data的数据一次性输入csv文件
    writer.writerows(data)

print("BMI计算数据已保存至", filename)
